package com.istock.user.controller.vue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.Constants;
import com.istock.union.user.model.DeptInfo;
import com.istock.union.user.model.SSOUser;
import com.istock.union.user.model.SecurityChecker;
import com.istock.union.user.model.ext.ExtMenuInfo;
import com.istock.union.user.service.DeptInfoService;
import com.istock.union.user.service.TenantInfoService;
import com.istock.user.model.DeptInfoVo;

@Controller
@RequestMapping("/s/deptInfo")
public class VueDeptInfoController {

	@Autowired
	private TenantInfoService tenantInfoService;
	@Autowired
	private DeptInfoService deptService;
	
	@SecurityChecker("user:deptInfo:search")
	@RequestMapping("/deptInfoInit")
	@ResponseBody
	public ApiBaseResponse<Map<String , Object>> deptInfoInit() {
		ModelMap model = new ModelMap();

		// 如果超级管理员时需要给出可选租户
		if (SSOClientUtils.getInstance().isAdmin()) {
			model.put("tenants", tenantInfoService.findAllTenantList());
			model.put("isAdmin", true);
		} else {
			model.put("isAdmin", false);
		}

		return new ApiBaseResponse<Map<String , Object>>( RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,
				Constants.API_RESPONSE_SUCCESS_MESSAGE, model);
	}
	
	
	@SecurityChecker("user:deptInfo:search")
	@RequestMapping("/searchToTree")
	@ResponseBody
	public ApiBaseResponse<List<DeptInfoVo>> searchToTree(String deptName , String deptCode) {
		SSOUser user = SSOClientUtils.getInstance().findCurrentUser();

		List<DeptInfoVo> listVo = new ArrayList<>();
		// 根据当前用户，查询出结果
//		List<DeptInfo> list = deptService.search(deptInfo);
		String currentDeptCode = user.getCurrentDept() != null ? user.getCurrentDept().getDeptCode() : "";
		List<DeptInfo> list = deptService.queryDeptTree(user.getTenantNo(), currentDeptCode, deptName, deptCode);
		for (DeptInfo d : list) {
			DeptInfoVo deptInfoVo = new DeptInfoVo();
			BeanUtils.copyProperties(d, deptInfoVo);
			listVo.add(deptInfoVo);
		}

		// 操作选项是否显示处理
		if (!SSOClientUtils.getInstance().isAdmin()) {
			List<String> set = new ArrayList<>();
//			deptService.getAncestorId(user.getCurrentDept().getId(), set);
			List<DeptInfo> deptList = deptService.findAncestorDept(user.getCurrentDept().getDeptCode(), currentDeptCode);
//			set.remove(user.getBelongDept().getId());
			for (DeptInfo d : deptList) {
				DeptInfoVo deptInfoVo = new DeptInfoVo();
				BeanUtils.copyProperties(d, deptInfoVo);
				listVo.add(deptInfoVo);
			}
			for (DeptInfoVo d : listVo) {
				if (set.contains(d.getId())) {
					d.setShowOper(false);
				} else {
					d.setShowOper(true);
				}
			}
		} else {
			for (DeptInfoVo d : listVo) {
				d.setShowOper(true);
			}
		}

		// 整理成树形结构
		List<DeptInfoVo> result = new ArrayList<>();
		for (DeptInfoVo item : listVo) {
			if (item.getParentId().equals("0")) {
				result.add(item);
				insertChild(item, listVo);
			}
		}

		return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
				Constants.API_RESPONSE_SUCCESS_MESSAGE, result);
	}
	
	void insertChild(DeptInfoVo source, List<DeptInfoVo> totalDate) {
		List<DeptInfoVo> children = new ArrayList<>();

		String parentId = source.getId();
		for (DeptInfoVo item : totalDate) {
			if (item.getParentId().equals(parentId)) {
				children.add(item);
				insertChild(item, totalDate);
			}
		}

		if (children != null && children.size()>0) {
			source.setChildren(children);
		}
	}
	
	@RequestMapping("/queryTenantDeptTreeData")
	@ResponseBody
	public ApiBaseResponse<List<Map<String, Object>>> queryTenantDeptTreeData(String deptId) {
		// 给定页面能够选择的组织机构树
		SSOUser user = SSOClientUtils.getInstance().findCurrentUser();
		/*if (StringUtils.isNotBlank(tenantCode) && StringUtils.isNotBlank(deptCode)) {
			user.setTenantCode(tenantCode);
			user.getLoginDept().setTenantCode(tenantCode);
		}*/
		String currentDeptCode = user.getCurrentDept() != null ? user.getCurrentDept().getDeptCode() : "";
		List<Map<String, Object>> trees = deptService.queryDeptTreeData(user.getTenantNo(), currentDeptCode, SSOClientUtils.getInstance().isAdmin(), true);
		if (StringUtils.isNotBlank(deptId)) {
			for (Map<String, Object> map : trees) {
				if (map.get("id").equals(deptId)) {
					map.put("disabled", true);
				}
			}
		}
		return new ApiBaseResponse<List<Map<String, Object>>>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
				Constants.API_RESPONSE_SUCCESS_MESSAGE, queryChildren("0",trees));
	}
	
	@RequestMapping("/queryDeptTreeDataVue")
	@ResponseBody
	public ApiBaseResponse<List<Map<String, Object>>> queryDeptTreeDataVue(String deptId) {
		SSOUser user = SSOClientUtils.getInstance().findCurrentUser();
		String currentDeptCode = user.getCurrentDept() != null ? user.getCurrentDept().getDeptCode() : "";
		List<Map<String, Object>> trees = deptService.queryDeptTreeData(user.getTenantNo(), currentDeptCode, SSOClientUtils.getInstance().isAdmin(), true);
		return new ApiBaseResponse<List<Map<String, Object>>>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
				Constants.API_RESPONSE_SUCCESS_MESSAGE, queryChildren("0",trees));
	}
	
	private List<Map<String, Object>> queryChildren(String parentId, List<Map<String, Object>> treeData) {
		List<Map<String , Object>> infos = new ArrayList<Map<String ,Object>>();
		for (Map<String, Object> tree : treeData) {
			if (parentId.equals(tree.get("pId"))) {
				Map<String,Object> item = new HashMap<String ,Object>();
				if(tree.containsKey("id")) {
					item.put("id", tree.get("id"));
				}
				if(tree.containsKey("disabled")) {
					item.put("disabled", tree.get("disabled"));
				}
				if(tree.containsKey("name")) {
					item.put("name", tree.get("name"));
				}
				List<Map<String,Object>> childList = queryChildren(item.get("id")+"" , treeData);
				
				if(childList != null) {
					item.put("children", childList);
				}
				infos.add(item);
			}
		}
		return infos;
	}
}
